NiiVue Loading Examples¶

This example shows 3 different methods to load neuroimaging data into ipyniivue:

  1. load from local path
  2. load from url
  3. load from name + raw binary data

There's an additional extra example at the end that shows modifying raw data and loading it into ipyniivue.

In [1]:
import pathlib

import numpy as np

import ipyniivue

try:
    import nibabel as nib
except ModuleNotFoundError:
    !pip install nibabel
    import nibabel as nib

Load from Local Path¶

Download from GitHub, save locally, then load

In [2]:
nv1 = ipyniivue.NiiVue()

github_url = "https://github.com/niivue/niivue-demo-images/raw/main"

DATA_FOLDER = pathlib.Path("images")

ipyniivue.download_dataset(
    api_url=github_url,
    dest_folder=DATA_FOLDER,
    files=[
        "mni152.nii.gz",
    ],
)

nv1.load_volumes([{"path": DATA_FOLDER / "mni152.nii.gz"}])
nv1
mni152.nii.gz already exists.
Dataset downloaded successfully to images.
Out[2]:

Load from URL¶

Direct loading from web URL

In [3]:
nv2 = ipyniivue.NiiVue()

nv2.load_volumes([{"url": "https://niivue.com/demos/images/mni152.nii.gz"}])
nv2
Out[3]:

Load from Binary Data¶

Using Volume class with name + data parameters

In [4]:
nv3 = ipyniivue.NiiVue()

data = np.zeros((64, 64, 64), dtype=np.float32)
center = np.array([32, 32, 32])
for i in range(64):
    for j in range(64):
        for k in range(64):
            dist = np.sqrt(
                (i - center[0]) ** 2 + (j - center[1]) ** 2 + (k - center[2]) ** 2
            )
            if dist < 20:
                data[i, j, k] = 1.0 - (dist / 20.0)

affine = np.eye(4)
nifti = nib.Nifti1Image(data, affine)

nifti_bytes = nifti.to_bytes()

volume = ipyniivue.Volume(name="sphere.nii", data=nifti_bytes)
nv3.load_volumes([volume])
nv3
Out[4]:

Extra example¶

Load with nibabel, modify by adding vertical rod, then pass binary data to ipyniivue

In [5]:
nv4 = ipyniivue.NiiVue()

img = nib.load(DATA_FOLDER / "mni152.nii.gz")
data = img.get_fdata()

max_val = data.max()
x_center = data.shape[0] // 2
y_center = data.shape[1] // 2

for z in range(20, data.shape[2] - 20):
    for dx in range(-3, 4):
        for dy in range(-3, 4):
            if dx * dx + dy * dy <= 9:
                data[x_center + dx, y_center + dy, z] = max_val * 2

modified_nifti = nib.Nifti1Image(data.astype(np.float32), img.affine, img.header)

nifti_bytes = modified_nifti.to_bytes()

volume = ipyniivue.Volume(name="modified_mni.nii", data=nifti_bytes)
nv4.load_volumes([volume])
nv4
Out[5]: